import angular from 'angular';

ngRowDirective.$inject = [];

function ngRowDirective() {
  return {
    restrict: 'E',
    transclude: true,
    template: '<div class="ng-row" ng-transclude></div>',
    scope: {
      gutter: '=?',     // 栅格间距（像素）
      justify: '@?',    // 水平对齐：start, end, center, space-between, space-around
      align: '@?'       // 垂直对齐：top, middle, bottom
    },
    link: function(scope, element) {
      var rowElement = element.find('div')[0] || element[0];

      // 默认值
      scope.gutter = scope.gutter || 0;
      scope.justify = scope.justify || 'start';
      scope.align = scope.align || 'top';

      // 设置 gutter
      function updateGutter() {
        var gutterValue = parseInt(scope.gutter) || 0;

        if (gutterValue > 0) {
          // 设置行的负边距
          angular.element(rowElement).css({
            'margin-left': -(gutterValue / 2) + 'px',
            'margin-right': -(gutterValue / 2) + 'px'
          });

          // 设置 CSS 变量供列使用
          angular.element(rowElement).css('--row-gutter', gutterValue + 'px');
        } else {
          angular.element(rowElement).css({
            'margin-left': '0',
            'margin-right': '0',
            '--row-gutter': '0px'
          });
        }
      }

      // 设置对齐方式
      function updateAlignment() {
        var rowEl = angular.element(rowElement);

        // 移除所有对齐类
        rowEl.removeClass('ng-row--justify-start ng-row--justify-end ng-row--justify-center ng-row--justify-space-between ng-row--justify-space-around');
        rowEl.removeClass('ng-row--align-top ng-row--align-middle ng-row--align-bottom');

        // 添加 justify 类
        if (scope.justify) {
          rowEl.addClass('ng-row--justify-' + scope.justify);
        }

        // 添加 align 类
        if (scope.align) {
          rowEl.addClass('ng-row--align-' + scope.align);
        }
      }

      // 监听 gutter 变化
      scope.$watch('gutter', function(newVal) {
        updateGutter();
      });

      // 监听对齐方式变化
      scope.$watch('justify', function(newVal) {
        updateAlignment();
      });

      scope.$watch('align', function(newVal) {
        updateAlignment();
      });

      // 初始化
      updateGutter();
      updateAlignment();
    }
  };
}

export default ngRowDirective;
